from django.contrib.auth.backends import ModelBackend
import re

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }
def get_user_by_account(account):
    try:
        if re.match(r'^1[]3-9]\d{9}$',account):
            user = User.objects.get(mobile = account)
        else:
            user = User.objects.get(username= account)
    except User.DoesNotExist:
        return None
    else:
        return user
class UsernameMobileAuthBackend(ModelBackend):
    # 自定义多账号登陆
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 使用用户名和手机号查询信息

        user = get_user_by_account(username)
        # 如果用户和用户密码检验通过后，返回user
        if user and user.check_password(password):
            return user